                         package com.wlzg.collectiontool.net

import android.text.TextUtils
import android.util.Log
import com.google.gson.GsonBuilder
import com.wlzg.collectiontool.App
import com.wlzg.collectiontool.BuildConfig
import com.wlzg.collectiontool.constant.Constant
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

class ApiStore {
     var apiService: ApiService? = null

    constructor() {
        apiService = createService()
    }

    companion object {
        val instance: ApiStore by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            ApiStore()
        }
    }

    /**
     * 创建 retrofit 客户端
     */
    private fun createService(): ApiService? {
        val gson = GsonBuilder().setDateFormat("yyyy.MM.dd HH:mm:ss").create()
        val httpBuilder = OkHttpClient.Builder()
        httpBuilder.connectTimeout(15, TimeUnit.SECONDS).readTimeout(15, TimeUnit.SECONDS)
            .writeTimeout(15, TimeUnit.SECONDS)

        //添加设置工共请求头的拦截器
        httpBuilder.addInterceptor(Interceptor { chain: Interceptor.Chain ->
            val original = chain.request()
            if (!TextUtils.isEmpty(App.getToken())) {
                val requestBuilder =
                    original.newBuilder().addHeader("token", App.getToken())
                val request = requestBuilder.build()
                return@Interceptor chain.proceed(request)
            }
          return@Interceptor  chain.proceed(original)
        })

        if (BuildConfig.DEBUG) {
            val loggingInterceptor = HttpLoggingInterceptor { message ->
                Log.d(
                    "OKHttp__",
                    message
                )
            }
            loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
            httpBuilder.addInterceptor(loggingInterceptor)
        }
        val retrofit: Retrofit = Retrofit.Builder()
            .baseUrl(Constant.baseUrl)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .client(httpBuilder.build())
            .build()
        return retrofit.create(ApiService::class.java)
    }
}